package club.justwill.single.Service.impl;

import club.justwill.single.Service.AuditService;
import club.justwill.single.bean.AuditBean;
import club.justwill.single.model.*;
import club.justwill.single.persistence.dao.AuditDao;
import club.justwill.single.persistence.dao.ProjectDao;
import club.justwill.single.persistence.jpo.Audit;
import club.justwill.single.persistence.jpo.Projects;
import club.justwill.single.util.JsonResponseHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


/**
 * Created by jaylon on 16-1-20.
 */
@Service
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class AuditServiceImpl implements AuditService{
    @Autowired
    private AuditDao auditDao;

    @Autowired
    private ProjectDao projectDao;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, noRollbackFor = Throwable.class, readOnly = false)
    public void auditProject(JsonResponse obj, SecurityToken token, AuditBean auditBean) {
        Audit audit = new Audit();
        Audit ad = auditDao.getByProjectId(auditBean.getProjectId());
        Projects project = projectDao.getByProjectId(auditBean.getProjectId());
        if(auditBean.getAuditStatus() == AuditType.STATUS_AUDITING || auditBean.getAuditStatus() == AuditType.STATUS_FAIL || auditBean.getAuditStatus() == AuditType.STATUS_PASS) {
            if(ad !=null && ad.getAuditId()!=0){
                ad.setStatus(auditBean.getAuditStatus());
                ad.setReason(auditBean.getReason());
                auditDao.update(ad,token);
            }else{
                ad.setStatus(auditBean.getAuditStatus());
                ad.setReason(auditBean.getReason());
                auditDao.save(audit,token);
            }
            project.setStatus(ProjectType.STATUS_CROW);
            projectDao.update(project,token);
        }else{
            JsonResponseHelper.addError(obj, CoreConstants.AUDIT_STATUS_ERROR);
        }

    }
}
